package cn.endeavour.org.service.impl;

import cn.endeavour.basic.service.impl.BaseServiceImpl;
import cn.endeavour.org.domain.Department;
import cn.endeavour.org.mapper.DepartmentMapper;
import cn.endeavour.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> getDeptTree() {
        return departmentMapper.getDeptTree();
    }

    @Transactional
    @Override
    public void add(Department department) {
        departmentMapper.save(department);
        // 如果没有选择上级部门
        if(department.getParent() == null || department.getParent().getId() == null){
            // 只添加自己的id - 自增长id
            department.setDirPath("/"+department.getId());
        }else{
            // 获取上级部门id
            Long parent_id = department.getParent().getId();
            // 获取上级部门的dirPath
            String parent_dirPath = departmentMapper.loadById(parent_id).getDirPath();
            // 组装自己的id
            department.setDirPath(parent_dirPath+"/"+department.getId());
        }
        // 更新到数据库
        departmentMapper.update(department);
    }

    @Transactional
    @Override
    public void update(Department department) {
        if(department.getParent() == null || department.getParent().getId() == null){
            department.setDirPath("/"+department.getId());
        }else{
            Long parent_id = department.getParent().getId();
            String parent_dirPath = departmentMapper.loadById(parent_id).getDirPath();
            // 对上级部门的处理
            if(parent_dirPath.indexOf(department.getId().toString())!=-1){
                throw new RuntimeException("上级部门不能选择自己");
            }
            department.setDirPath(parent_dirPath+"/"+department.getId());
        }
        departmentMapper.update(department);
    }
}
